package com.zly.demo.redislimit.aop;

import com.zly.demo.redislimit.annotation.RedisLimit;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collections;

@Slf4j
@Aspect
@Component
public class RedisLimitAop {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private DefaultRedisScript<Long> script;

    @PostConstruct
    public void init() {
        script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis.lua")));
        log.info("redis limit init");
    }

    @Around("@annotation(com.zly.demo.redislimit.annotation.RedisLimit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLimit annotation = method.getAnnotation(RedisLimit.class);
        if (annotation != null) {
            log.info("in   ...");
            String key = annotation.key();
            long limit = annotation.limit();
            long expire = annotation.expire();
            Long result = stringRedisTemplate.execute(script, Collections.singletonList(key), String.valueOf(limit), String.valueOf(expire));
            if (result == 1) {
                log.info("redis limit success");
                return joinPoint.proceed();
            } else {
                log.info("redis limit fail");
                return annotation.msg();
            }
        }
        log.info("redis limit");
        return joinPoint.proceed();
    }
}
